package cn.duwey.scs.common.util;

import java.beans.PropertyDescriptor;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.BeansException;

public class BeanUtils {

    public static final String[] COPY_IGNORED_PROPERTIES = {"id", "rowVersion", "isDeleted",
            "createBy", "createDate", "modifiedDate"};

    public static void copyProperties(Object source, Object target) throws BeansException {
        org.springframework.beans.BeanUtils.copyProperties(source, target);
    }

    public static void copyPropertiesIgnoreNull(Object source, Object target)
            throws BeansException {
        org.springframework.beans.BeanUtils
                .copyProperties(source, target, getNullPropertyNames(source));
    }

    public static void copyEntityProperties(Object source, Object target) throws BeansException {
        org.springframework.beans.BeanUtils.copyProperties(source, target, COPY_IGNORED_PROPERTIES);
    }

    public static void copyEntityPropertiesIgnoreNull(Object source, Object target)
            throws BeansException {
        org.springframework.beans.BeanUtils
                .copyProperties(source, target, getNullAndEntityIgnoredPropertyNames(source));
    }

    public static void copyProperties(Object source, Object target, String... ignoreProperties)
            throws BeansException {
        org.springframework.beans.BeanUtils.copyProperties(source, target, ignoreProperties);
    }

    private static String[] getNullPropertyNames(Object source) {
        Set<String> emptyNames = getNullPropertyNamesSet(source);
        String[] result = new String[emptyNames.size()];
        return emptyNames.toArray(result);
    }

    private static String[] getNullAndEntityIgnoredPropertyNames(Object source) {
        Set<String> emptyNames = getNullPropertyNamesSet(source);
        emptyNames.addAll(Arrays.asList(COPY_IGNORED_PROPERTIES));
        String[] result = new String[emptyNames.size()];
        return emptyNames.toArray(result);
    }

    private static Set<String> getNullPropertyNamesSet(Object source) {
        final BeanWrapper src = new BeanWrapperImpl(source);
        PropertyDescriptor[] pds = src.getPropertyDescriptors();

        Set<String> emptyNames = new HashSet<String>();
        for (PropertyDescriptor pd : pds) {
            Object srcValue = src.getPropertyValue(pd.getName());
            if (srcValue == null) {
                emptyNames.add(pd.getName());
            }
        }

        return emptyNames;
    }

}
